package ferp.center.server.task;

import com.google.appengine.api.taskqueue.TaskHandle;
import ferp.center.server.Action;
import ferp.center.server.entity.Rating;
import ferp.center.server.ranking.Ranker;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

/**
 * User: igorgok
 * Date: 6/6/13 12:24 PM
 */
public class TaskRangeTreeDelete extends HttpServlet
{
  public static void queue(String configuration)
  {
    TaskHandle t = configuration == null || configuration.length() == 0?
        Ranker.queue().add(withUrl(URL)) :
        Ranker.queue().add(withUrl(URL).param(CFG, configuration));

    System.out.println("queued tree delete, handle=" + t.toString());
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, new Action.Task()
    {
      @Override
      protected void run(EntityManager em, HttpServletRequest request) throws IOException
      {
        System.out.println("ranges deleted " + em.createQuery("DELETE FROM Range").executeUpdate());
        System.out.println("trees deleted " + em.createQuery("DELETE FROM RangeTree").executeUpdate());

        detachRatings(em);
      }
    });
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    queue(null);
  }

  private static void detachRatings(EntityManager em)
  {
      List<Rating> ratings = em.createQuery("SELECT r FROM Rating r WHERE r.range is not null").getResultList();
      System.out.println("ratings to detach " + ratings.size());

      for (Rating r : ratings)
        em.find(Rating.class, r).setRange(null);

      System.out.println("ratings have been detached");
  }

  private static final String URL = Url.rt("delete");
  private static final String CFG = "cfg";
}
